#coding=utf-8

#	Socket连接管理 
#	1: 监听客户端socket连接是否正常 
#	2：中转客户端socket在第一次战斗中所发消息
#	3：向其它服务器中转解析后消息 

from twisted.internet.protocol import Factory,Protocol
import message
import mg_master
import mg_zone


class CS_Protocol(Protocol):

	def connectionMade(self):
		pass

	def connectionLost(self,reason):
		self.factory.removeFromSockets(self)

#如果是需要cs管理连接，undata有值，其它为None
	def dataReceived(self,data):
		undata,all = message.getThePrefectObject(data,self,self.factory.getUserIdBySocket(self))
		print "<-- Server to Client --> :",undata,all
		if undata:
			if undata != None and all == "fullarmy":
				self.factory.sendAllUserInOneRoom(undata,self)
			else:
				self.transport.write(undata)

class connection_server(Factory):
	
	protocol = CS_Protocol

	def __init__(self):
		self.sockets = {}   #存储客户端socket连接对象
		self.ids = {}

	def addToSockets(self,userid,socket):
		print "<-- SocketServer add a client --> ",userid
		self.sockets[socket] = userid
		self.ids[userid] = socket	

	def removeFromSockets(self,socket):
		if self.sockets.has_key(socket):
			idvalue = self.sockets[socket]
			#cahe清空user对象
			mg_master.cache.removeUser(idvalue)
			del self.sockets[socket]
			del self.ids[idvalue]
			print "<-- Client disconnected -->",idvalue
	

	def getUserIdBySocket(self,socket):
		try:
			return self.sockets[socket]
		except:
			return None

	def sendAllUserInOneRoom(self,undata,socket):
		userid = self.sockets[socket]
		user = mg_master.cache.getUser(userid)
		roomid = user.getRoomId()
		users = mg_zone.getUsersByRoomId(roomid)
		for user in users:
			socket  = self.ids[user.getId()]
			socket.transport.write(undata)
				

#返回连接
cs = connection_server() 
def getFactory():
	return cs

#验证通过后加入到Socket管理中
def vertifiedAddToSockets(user,pro):
	cs.addToSockets(user.getId(),pro)

